package com.frxuexi.shop

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.frxuexi.lib_base.entity.ProductBeanItem
import com.frxuexi.lib_base.net.ShopApiService
import java.lang.Exception
import java.lang.RuntimeException

class ShopDataSource(val apiService: ShopApiService):PagingSource<Int, ProductBeanItem>() {
    override fun getRefreshKey(state: PagingState<Int, ProductBeanItem>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ProductBeanItem> {
        return try {
            //获取当前页码
            val currentPage=params.key?:1
            val products = apiService.getProducts(1, 6, currentPage)
            val preKey=if(currentPage>1)currentPage-1 else null


            if(products.code==200) {
                val nextKey=if(currentPage<products.data.totalPage)currentPage+1 else null
//                val nextKey=if(products.data.list.size!=0)currentPage+1 else null
                return LoadResult.Page(products.data.list, preKey, nextKey)
            }else{
                return LoadResult.Error(RuntimeException(products.message))
            }
        }catch (e:Exception){
            return LoadResult.Error(e)
        }
    }
}